$m(function (args) {
    var $this = $(this.element).closest("body");
    var editStatus = false;
    var paramAccordion = $this.find("#tempo-mine-paraminfo-accordion");
    var controller = new MinePublishServiceController(themeId);
    controller.serviceDialog = $('.app-config-container');
    controller.service = {};
    controller.service.id = serviceId;
    controller.service.themeId = themeId;
    var target = controller.serviceDialog.find('input[name=flow]');
    controller.flowSelectHandler(target, null, function (result) {
        controller.serviceDialog.find('input[name=paramName]').width('150px');
        if (result || result.length == 0) {
            controller.serviceDialog.find('#serviceParamGrid').text(TempoUtils.locale('ai.none'));
        }
    });
    var locale = TempoUtils.locale;
    var types = {
        async: TempoUtils.locale("mine.yibu"),
        sync: TempoUtils.locale("mine.tongbu"),
        stream: TempoUtils.locale("mine.liu")
    };
    $('.service-type').text(types[row.type]);
    //配置按钮的事件--添加权限
    $('a.config-button').button({
        click: function () {

            var $clickDom = $(this);
            if (!!row.launchState && row.launchState != 'NONE') {
                $("<div/>").alert({msg: locale('aiview.stop-first')});
                return;
            }
            var form = $this.find("#tempo-mine-flow-service-test");
            //其他按钮置灰
            $('a.start-button').addClass("config_abutton_disabled");
            $('a.test-button').addClass("config_abutton_disabled");
            $('a.down-sdk-button').addClass("config_abutton_disabled");
            $('a.down-ex-button').addClass("config_abutton_disabled");
            $this.find("#resourceParamConfigTab input").attr("disabled", "disabled");
            if (!editStatus) {
                configInitEdit.call(this);//初始化配置页面
                $("button[id='instance-add']").attr("disabled", "true").css("opacity", " 0.2").css("cursor", "default");
                $this.find("#resourceParamConfigTab input").removeAttr("disabled", "disabled");
            } else {
                if (!form.formValidate()) {
                    TempoUtils.showTip(TempoUtils.locale("aiview.configtip"));
                    return;
                }
                //保存事件
                var rowNew = TempoUtils.clone(row);
                rowNew.name = controller.serviceDialog.find('input[name=name]').val();
                rowNew.serviceAlias = controller.serviceDialog.find('input[name=serviceAlias]').val();
                // rowNew.serviceAlias = $('input[name=serviceAlias]').val();
                rowNew.interDescript = controller.serviceDialog.find('input[name=IDesName]').val();
                //存储最新的流程参数+资源环境参数
                Eventbus.trigger("saveFlowParamGrid.mine", $this.find("#flow-params"), $this.find("#res-config"), rowNew);
                Eventbus.trigger("saveApiServiceConfig.mine", rowNew, true, function (data) {
                    if (data && data.status) {
                        row = rowNew;
                        configInitSave.call($clickDom);//保存页面后的重新渲染
                        $('a.start-button').removeClass("config_abutton_disabled");
                        $('a.test-button').removeClass("config_abutton_disabled");
                        $('a.down-sdk-button').removeClass("config_abutton_disabled");
                        $('a.down-ex-button').removeClass("config_abutton_disabled");
                    } else {
                        $("<div/>").alert({
                            msg: TempoUtils.locale("mine.publish-savefailed") + data.error,
                            height: 180,
                            width: 400
                        });
                    }
                });
                $("button[id='instance-add']").removeAttr("disabled");
                $("button[id='instance-add']").css("opacity", " 1").css("cursor", "pointer")
            }
        }
    });

    //启动/停止操作 还是需要传启动参数的[方便复用旧的系统接口] --添加权限
    if (!!row.launchState && row.launchState != 'NONE') {
        $('a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
    } else {
        $('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
    }
    $('a.start-button').button({
        click: function () {
            var that = $this;

            if (row.type == 'sync' || row.type == 'stream') {
                if (!!row.launchState && row.launchState != 'NONE') {
                    var msg = TempoUtils.locale("mine.shifotingzhitongbufuwu");
                    if (row.type == "stream") {
                        msg = TempoUtils.locale("mine.shifotingzhiliufuwu");
                    }
                    $("<div/>").confirm({
                        title: TempoUtils.locale("mine.prompt"),
                        msg: msg,
                        ok: function () {
                            $('a.start-button').addClass("ui-state-disabled");
                            operateStart(row);//启动操作
                        }
                    })
                } else {
                    if (row.type == 'sync') {
                        if (authCodes == null || authCodes && authCodes.length == 0) {
                            TempoUtils.showTip(TempoUtils.locale("aiview.configtip2"));
                            return;
                        }
                    }
                    operateStart(row);//启动操作
                }
            }
        }
    });
    if (row.type && row.type == "async") {
        $('a.start-button').hide();
        $(".sync-api-desc").hide()
        $(".async-api-desc").show();
    }
    if (row.type && row.type == "stream") {
        $('a.down-ex-button').hide();
        $('a.down-sdk-button').hide();
        $(".async-api-desc").hide();
        $(".sync-api-desc").hide()
        //调整服务配置信息页显示内容
        //隐藏请求参数说明，返回参数说明，js示例代码
        $("#tempo-mine-paraminfo-accordion").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(2)").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(4)").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(5)").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(6)").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(7)").hide();
        $(".tempo-mine-flow-service-info-table tr:nth-child(8)").hide();
    }
    //测试页面操作
    $('a.test-button').button({
        click: function () {
            var eventName = '';
            if (row.type == 'sync') {
                eventName = 'testSyncFlow.mine';
            } else if (row.type == 'async') {
                eventName = 'testAsyncFlow.mine';
            }
            if (eventName) {
                Eventbus.trigger(eventName, row);
            }
        }
    });
    //下载sdk按钮操作
    $('a.down-sdk-button').button({
        click: function (e) {
            TempoUtils.download({
                url: contextPath + '/api/ai/mine/sync/sdk',
                data: {
                    id: row.id
                }
            });
            var btn = $(this).button('disable');
            setTimeout(function () {
                btn.button('enable');
            }, 5000);
            return false;
        }
    });
    //下载示例代码按钮操作
    $('a.down-ex-button').button({
        click: function (e) {
            TempoUtils.download({
                url: row.type != 'sync' ? contextPath + '/api/ai/mine/async/clientcode' : contextPath + '/api/ai/mine/sync/clientcode',
                data: {
                    id: row.id,
                    flowid: row.flowid
                }
            });
            var btn = $(this).button('disable');
            setTimeout(function () {
                btn.button('enable');
            }, 5000);
            return false;
        }
    });
    if (row.type == 'sync') {
        //下载公共包
        $('a.mine-service-runtime-download').button({
            label: TempoUtils.locale('mine.publish-runtime-download'),
            click: function () {
                TempoUtils.download({
                    url: contextPath + "/api/ai/mine/sync/downloadRuntimeJars",
                    data: {}
                });
            }
        }).show();
        //下载服务包
        $('a.mine-service-resource-download').button({
            label: TempoUtils.locale('mine.publish-sync-resource-title'),
            click: function () {
                TempoUtils.download({
                    url: contextPath + "/api/ai/mine/sync/downloadSyncResource/" + row.id,
                    data: {}
                });
            }
        }).show();
        $('.mine-service-resource-label').show();
        $(".async-api-desc").hide();
        $(".sync-api-desc").show();
    }
    //启动流服务/同步服务
    var operateStart = function () {
        var that = $this;
        var cpu = that.find('#res-config input[name=cpu]').val();
        var mem = that.find('#res-config input[name=memory]').val();
        var mode = that.find('#res-config select[name=mode]').selectmenu('getValue');
        operateFlow.apply(that, [row, {cpu: cpu, mem: mem, mode: mode}]);
    }
    // 请求服务状态
    var isAlive = function (fn, uid) {
        var id = uid || row.id
        $.postForm({
            url: contextPath + '/api/ai/app/model/status/' + id,
            success: function (rp) {
                fn(rp.data == 'STARTING' || rp.data == 'RUNNING', rp.data);
            }
        });
    }
    var updateStatusLoop = function (id, updateFn, type) {
        Eventbus.trigger('updateStatusLoop.service', id, updateFn, type);
    }
    // 启动或停止
    var operateFlow = function (row, setting) {

        var requestId = null;
        if (authCodes.length != 0) {
            requestId = window.btoa(authCodes[0].clientCode + "#" + authCodes[0].skCode + "#" + new Date().getTime());
        } else {
            requestId = window.btoa(new Date().getTime());
        }
        var id = row.id, flowid = row.flowid, status = row.launchState;
        var flowParam = "[]";
        var flowArray = resPar.filter(function (v) {
            if (v.paramName === "system.appId") {
                return false;
            } else if (v.$configResources$ == null) {
                return true;
            }
        });
        if (flowArray != undefined && flowArray != null) {
            flowParam = JSON.stringify(flowArray);
        }
        var param = {
            mode: setting.mode || row.mode,
            cpu: setting.cpu || 2,
            mem: setting.mem || 2,
            requestId: requestId,
            flowparam: flowParam
        };
        //var process = $("<div/>").tempoprogressbar();
        var counter = status == 'RUNNING' ? 25 : 0;
        // 最终服务应该呈现的状态
        var finalTag = (status == 'RUNNING' || status == 'STARTING') ? false : true;
        var op = finalTag ? "start" : "stop";
        if (op == "stop") {
            param = {
                requestId: requestId,
            };
        }
        // 点击启动按钮或者停止按钮后，直接禁用按钮
        $('a.start-button').addClass("ui-state-disabled");
        $.postJson({
            url: contextPath + '/api/ai/app/model/' + op + "/" + id,
            data: param,
            success: function (d) {

                var serviceStatus = "";
                if (!d.success) {
                    $("<div/>").alert({msg: d.message});
                    //启动或停止失败，需要解除禁用状态。
                    $('a.start-button').removeClass("ui-state-disabled");
                    return;
                }
                if (op == "start") {
                    $('div[objid="' + id + '"] #ca-status').text(TempoUtils.locale("aiview.serviceStarting"));
                    $("div[objid='" + id + "'] #service_status").text(TempoUtils.locale("aiview.serviceStarting"));
                    serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, id);
                    $('a.start-button').addClass("ui-state-disabled");
                }
                updateStatus(op, finalTag, serviceStatus, counter);
            }
        });

    }
    /**
     * 更新服务状态信息
     */
    var updateStatus = function (op, finalTag, serviceStatus, counter) {
        var id = row.id;
        if (op == "start") {
            $('a.start-button').addClass("ui-state-disabled");
        }
        setTimeout(function () {
            var fn = arguments.callee;
            isAlive(function (d, status) {
                if (d == finalTag) {
                    row.launchState = status;
                    if (op == "start") {//status == 'STARTING'
                        setTimeout(function () {
                            var fn = arguments.callee;
                            isAlive(function (d, status) {
                                if (status == 'STARTING') {
                                    updateStatusLoop(row.id, null, row.type);
                                } else {
                                    //process.tempoprogressbar("destroy");
                                    row.launchState = status;
                                    $('a.start-button').text(TempoUtils.locale("aiview.serviceStop"));
                                    $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceHasStart"));
                                    $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceHasStart"));
                                    serviceStatus = TempoUtils.locale("aiview.serviceHasStart");
                                    Eventbus.trigger('updateserviceStatus.service', serviceStatus, row.id);
                                    $('a.start-button').removeClass("ui-state-disabled");
                                    var profx = $this.find("#res-config");
                                    profx.find('#mine-opt-instance-grid').datagrid("reloadGrid");
                                }
                            }, id);
                        }, 1000);
                    } else if (op == "stop") {
                        //process.tempoprogressbar("destroy");
                        $('a.start-button').text(TempoUtils.locale("aiview.serviceStart"));
                        $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
                        $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceUnStart"));
                        serviceStatus = TempoUtils.locale("aiview.serviceUnStart");
                        Eventbus.trigger('updateserviceStatus.service', serviceStatus, row.id);
                        $('a.start-button').removeClass("ui-state-disabled");
                        var profx = $this.find("#res-config");
                        profx.find('#mine-opt-instance-grid').datagrid("reloadGrid");
                    }
                } else {
                    counter++;
                    if (op == "start") {
                        $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceStarting"));
                        $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceStarting"));
                        serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                    }
                    if (counter < 30) {
                        setTimeout(fn, 1000);
                    } else {
                        var process = $("<div/>").tempoprogressbar();
                        process.tempoprogressbar("destroy");
                        row.launchState = status;
                        if (status != "RUNNING" && status != "STARTING") {
                            $("div[objid='" + row.id + "'] #ca-status").text(TempoUtils.locale("aiview.serviceUnStart"));
                            $("div[objid='" + row.id + "'] #service_status").text(TempoUtils.locale("aiview.serviceUnStart"));
                            serviceStatus = TempoUtils.locale("aiview.serviceStarting");
                            var profx = $this.find("#res-config");
                            profx.find('#mine-opt-instance-grid').datagrid("reloadGrid");
                        } else if (status == "STARTING") {
                            // 继续进行状态查询
                            updateStatusLoop(row.id, null, row.type);
                        }
                        Eventbus.trigger('updateserviceStatus.service', serviceStatus, row.id);
                    }
                }
            }, id);
        }, 3000);
    }


    /**
     * 创建折叠面板及其样式
     */
    var createAccordion = function () {
        paramAccordion.accordion({
            collapsible: true,
            heightStyle: "content",
            fillSpace: true
        });
    }

    //保存页面后的重新渲染
    var configInitSave = function () {
        var that = $this;
        $(this).text(locale('aiview.do-config'));
        editStatus = false;
        that.find('td[name="serviceName"]').text(row.name);
        that.find('td[name="async-test-data-alias"]').text(row.serviceAlias);
        that.find('td[name="async-test-data-explain"]').text(row.interDescript);
        loadAlias();
        //授权的渲染
        loadCode();
        //cpu等编辑框的关闭
        //资源环境参数和流程参数的编辑
        that.find("#serviceParamConfig input").attr("disabled", "disabled");
        that.find("#res-config select.tempo-selectmenu").selectmenu("option", "disabled", true);
        that.find("#flow-params select.tempo-selectmenu").selectmenu("option", "disabled", true);
        Eventbus.trigger('updateName.service', row);
    }
    //点击配置触发编辑事件的init函数
    var configInitEdit = function () {
        var that = $this;
        $(this).text(locale('aiview.save-config'))
        editStatus = true;
        //服务名称的编辑
        var box = that.find('td[name="serviceName"]').empty();
        var input = $('<input name="name" />').val(row.name).appendTo(box);
        var aliasBox = that.find('td[name="async-test-data-alias"]').empty();
        var aliasInput = $('<input name="serviceAlias" />').val(row.serviceAlias).appendTo(aliasBox);
        input.validatebox({
            required: true,
            width: '200px',
            maxLength: 60,
            validator: true,
            autofill: false
//			tip:TempoUtils.locale("aiview.serviceNameValidError")
            //valids:[/^(\w|[\u4e00-\u9fa5]|_){1,30}$/g]
//			valids:[/^[^~!@#\$%\^&\*\+\[\]\|\}\{\\;':",\.\/<>\?`]+$/]
        });
        input.focus();
        aliasInput.validatebox({
            required: false,
            width: '200px',
            maxLength: 60,
            validator: true,
            autofill: false,
            tip: TempoUtils.locale("aiview.serviceAlias"),
            valids: [/^\w{1,60}$/]
        })
        aliasInput.focus();
        //授权的编辑
        var grantList = that.find('td[name="grantList"]').empty();
        var btn = $("<button name='grantListBtn'>" + TempoUtils.locale("aiview.edit") + "</button>").appendTo(grantList);
        btn.button({
            click: function () {
                Eventbus.trigger('authorize-service.mine', row);
            }
        });
        //接口说明的编辑
        var IDescript = that.find('td[name="async-test-data-explain"]').empty();
        var inputDes = $('<input name="IDesName" />').val(row.interDescript).appendTo(IDescript);
        inputDes.validatebox({
            required: true,
            width: '200px',
            maxLength: 60,
            validator: true,
            autofill: false
        });
        //资源环境参数和流程参数的编辑
        that.find("#serviceParamConfig input").removeAttr("disabled");
        that.find("#res-config select.tempo-selectmenu").selectmenu("option", "disabled", false);
        that.find("#flow-params select.tempo-selectmenu").selectmenu("option", "disabled", false);
    }
    //初始化服务页面
    var initService = function (rowData) {
        //填充服务信息基本表格 以及 部分格式化
        var form = $this.find("#tempo-mine-flow-service-test");
        if (rowData.type == 'async') {
            //异步服务页面的初始化
            var tempoBaseUrl = urlPrefix + "/webapi/ai/model/async/execute/" + rowData.id;
            form.find('[name=async-test-data-url]').text(tempoBaseUrl);
        } else if (rowData.type == 'sync') {
            var btn = $('.status-button').show();
            $('.test-button').show();
            var tempoBaseUrl = urlPrefix + "/webapi/ai/model/sync/" + rowData.id;
            form.find('[name=async-test-data-url]').text(tempoBaseUrl);
            if (!!rowData.launchState && rowData.launchState != 'NONE') {
                btn.text(locale('aiview.stop-service'));
                if (rowData.launchState == 'STARTING') {
                    $('.service-status').text(locale('aiview.status-starting'));
                    $('a.start-button').addClass("ui-state-disabled");
                }
                if (rowData.launchState == 'RUNNING') $('.service-status').text(locale('aiview.status-running'));
            } else {
                btn.text(locale('aiview.start-service'));
                $('.service-status').text(locale('aiview.status-none'));
            }
        } else if (rowData.type == 'stream') {
            form.find(".clientCodeInfo").hide();
            form.find(".sync-test-fubm").hide();
            var btn = $('.status-button').show();
            $('.test-button').hide();
            if (!!rowData.launchState && rowData.launchState != 'NONE') {
                btn.text(locale('aiview.stop-service'));
                if (rowData.launchState == 'STARTING') {
                    $('.service-status').text(locale('aiview.status-starting'));
                    $('a.start-button').addClass("ui-state-disabled");
                }
                if (rowData.launchState == 'RUNNING') $('.service-status').text(locale('aiview.status-running'));
            } else {
                btn.text(locale('aiview.start-service'));
                $('.service-status').text(locale('aiview.status-none'));
            }
        }
        if (row.launchState == 'STARTING') {
            // 如果发现状态在启动中，需要更新
            /*$('a.start-button').addClass("ui-state-disabled");
            var tempoId= TempoUtils.uuid();
            //var process = $("<div id='"+tempoId+"'/>").tempoprogressbar();
            setTimeout(function() {
                var fn = arguments.callee;
                isAlive(function(d, status) {
                    if(status == 'STARTING') {
                        setTimeout(fn, 1500);
                    } else {
                        console.log(TempoUtils.locale("aiview.zhuxiao"))
                        //process.tempoprogressbar("destroy");
                        row.launchState = status;
                        //重新加载列表
                        $this.find("#ca-status").text(TempoUtils.locale("aiview.serviceHasStart"));
                        initService(row);
                    }
                });
            }, 1000);*/
            updateStatusLoop(row.id, null, row.type);
        }
        //加载流程参数和环境参数
        loadFlowParams(resPar);
        loadResParams(resPar);
    };

    //加载服务别名问题
    var loadAlias = function () {

        var form = $this.find("#tempo-mine-flow-service-test");
        var alias = $('td[name="async-test-data-alias"]');
        var lines = "";
        if (row.serviceAlias == null || row.serviceAlias.length == 0 || "" == row.serviceAlias) {
            alias.empty().text(TempoUtils.locale('aiview.alias'));
        } else {
            if (row.type == 'async') {
                lines = urlPrefix + "/webapi/ai/model/alias/async/execute/" + row.serviceAlias;
            } else if (row.type == 'sync') {
                lines = urlPrefix + "/webapi/ai/model/alias/sync/" + row.serviceAlias;
            }
            var str = "";
            var line = row.serviceAlias;
            line += "<a class='app-key-copy-btn' onclick='copyToClip(\"{line}\")'>[" + locale("mine.copy_address") + "]</a>"
            line += "<br/>";
            line = line.replace("{line}", lines);
            str += line;
        }
        alias.html(str);
    }
    // 加载授权码
    var loadCode = function () {
        var zone = $('td[name="grantList"]');
        if (authCodes == null || authCodes && authCodes.length == 0) {
            zone.empty().text(TempoUtils.locale('aiview.none'));
        } else {

            var str = "";
            var shortenStr = function (s) {
                return !!s ? s.substr(0, 8) + ".." : "";
            }
            authCodes.forEach(function (v, i) {
                var line = locale("mine.dyxtmc") + ":" + v.name + ", " + locale("mine.kehubiaoshi") + ":" + shortenStr(v.key) + ", " + locale("mine.shouquanma") + ": " + shortenStr(v.secret);
                line += "<a class='app-key-copy-btn' onclick='copyToClip(\"key:{key} secret:{secret}\")'>[" + locale("mine.copy") + "]</a>"
                line += "<br/>";
                line = line.replace("{key}", v.key);
                line = line.replace("{secret}", v.secret);
                str += line;
            });
            zone.html(str);
        }
    };
    // 复制key内容到剪贴板中
    window.copyToClip = function (s) {
        var aux = document.createElement("input");
        aux.setAttribute("value", s);
        document.body.appendChild(aux);
        aux.select();
        document.execCommand("copy");
        document.body.removeChild(aux);
        $("<div/>").alert({msg: locale('mine.copy_success')});
    }
    //保存为最新的授权码
    var saveAuth = function (rs) {
        authCodes = rs;
    }

    //加载流程参数
    var loadFlowParams = function (params) {

        if (params.length > 0) {
            var flowArray = params.filter(function (v) {
                if (v.paramName === "system.appId") {
                    return false;
                } else if (v.$configResources$ == null) {
                    return true;
                }
            });
            Eventbus.trigger("initFlowParamGrid.mine", $this.find("#flow-params"), flowArray);
        }
    }
    //加载资源环境参数
    var loadResParams = function (params) {
        if (params.length > 0) {
            var configRes = params.filter(function (v) {
                if (v.$configResources$ != null) {
                    return true
                }
            });
            if (configRes.length > 0) {
                //解析环境参数
                Eventbus.trigger("initResourcesPanel.mine", $this.find("#res-config"), configRes[0], row.type, serviceId);
                $this.find("#serviceParamConfig input").attr("disabled", "disabled");
                $this.find("#res-config select.tempo-selectmenu").selectmenu("option", "disabled", true);
                $this.find("#resourceParamConfigTab input").attr("disabled", "disabled");
            }
        }
    }


    Eventbus.one('authorize-save.mine', saveAuth);
    Eventbus.one('flow-service-status-update.mine', updateStatus);
    // 添加隐藏功能，下载同步服务的日志，调试启动过程报错问题
    var downloadSynclog = function () {
        TempoUtils.downLoadFile({
            url: contextPath + "/mine/sync/downloadonlinelog/" + serviceId,
            data: {}
        });
    };
    $this.find('.service-type').click(function (e) {
        if (e.ctrlKey && altKey) {
            downloadSynclog();
        }
    });
    var w = $this.find('.app-config-container').innerWidth();
    $this.find('.tempo-mine-flow-service-info').width(w * 0.4);
    $this.find('.tempo-mine-service-monitor-info').width(w * 0.4);

    initService(row);
    createAccordion();
    loadAlias();
    loadCode();
});